package com.lsq.common;

import java.io.File;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @author:罗苏琴
 * @Date 2024/12/13 下午3:43
 */
public class RequestMappingAnalysis {
    public static void main(String[] args) throws ClassNotFoundException {
        System.out.println(getRequestMapping("com.lsq.controller"));
    }

    public static Map getRequestMapping(String packageName) throws ClassNotFoundException {
        String basePath = RequestMapping.class.getResource("/").getPath() + "\\";

        String packStr = packageName.replace(".", "\\");

        File file = new File(basePath + packStr);

        Map<String, String> urlMap = new HashMap<String, String>();

        if (file.isDirectory()) { //当前路径为文件夹
            File[] files = file.listFiles(); //取出当前文件夹下的所有文件
            for (File file1 : files) {
                if (file1.isFile()) { //判断是否为文件

                    String className = packageName + "." + file1.getName();

                    className = className.substring(0, className.lastIndexOf("."));

                    Class clazz = Class.forName(className);

                    String baseUrl = "";
                    if (clazz.getAnnotation(RequestMapping.class) != null) {
                        RequestMapping typeAnno = (RequestMapping) clazz.getAnnotation(RequestMapping.class);
                        baseUrl = typeAnno.value();
                    }
                    Method[] methods = clazz.getMethods();
                    for (Method method : methods) {
                        if (method.getAnnotation(RequestMapping.class) != null) {
                            RequestMapping typeAnno = (RequestMapping) method.getAnnotation(RequestMapping.class);

                            String methodUrl = typeAnno.value();

                            urlMap.put(baseUrl + methodUrl, className + "." + method.getName());
                        }
                    }
                }
            }
        }
        return urlMap;
    }
}
